package cn.jksoft.businessclient.ui.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.inputmethodservice.KeyboardView;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jksoft.businessclient.R;
import cn.jksoft.businessclient.api.ReceivingApi;
import cn.jksoft.businessclient.api.ReceivingService;
import cn.jksoft.businessclient.base.BaseApplication;
import cn.jksoft.businessclient.base.BaseConfig;
import cn.jksoft.businessclient.base.BaseSwipeBackCompatActivity;
import cn.jksoft.businessclient.bean.AreaEntity;
import cn.jksoft.businessclient.bean.CustomerEntity;
import cn.jksoft.businessclient.bean.LocAreaInfoEntity;
import cn.jksoft.businessclient.bean.StoreCustEntity;
import cn.jksoft.businessclient.ui.adapter.PopupAdapter;
import cn.jksoft.businessclient.ui.views.CarNumberKeyBoardView;
import cn.jksoft.businessclient.utils.CommonUtils;
import cn.jksoft.businessclient.utils.Constants;
import cn.jksoft.businessclient.utils.DialogHelp;
import cn.jksoft.businessclient.widgets.RecyclerItemClickListener;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Author:  nick
 * Email:   nickdevp@gmail.com
 * Date:    16/4/7 14:38.
 * Description:
 */
public class ReceivingCarActivity extends BaseSwipeBackCompatActivity implements View.OnClickListener {


    @Bind(R.id.tv_car_province)
    TextView tvProvince;
    @Bind(R.id.tv_short_province)
    TextView tvCityCode;
    @Bind(R.id.et_car_no)
    EditText etCarNo;
    @Bind(R.id.tv_car_no)
    TextView tvCarNo;
    @Bind(R.id.keyboard_view)
    KeyboardView mKeyboardView;

    private String provinceId;
    private View rootArea, rootShortArea;
    private PopupWindow popupArea, popupShortArea;
    private StaggeredGridLayoutManager mLayoutManager,sLayoutManager;
    private PopupAdapter mAdapter,sAdapter;
    private ProgressDialog waitDialog;
    List<AreaEntity.DataEntity> areaList = new ArrayList<AreaEntity.DataEntity>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receiving_car);
        ButterKnife.bind(this);
        initTitle("接车");
        initBackClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        getLocAreaInfo();
    }

    private void initPopup() {

        if (rootArea == null || popupArea == null) {
            rootArea = getLayoutInflater().inflate(R.layout.popup_list, null);
            // 创建PopupWindow对象
            popupArea = new PopupWindow(rootArea, ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            // popupArea.setAnimationStyle(R.anim.in);
            popupArea.setBackgroundDrawable(new BitmapDrawable());// 点击窗口外消失
            popupArea.setOutsideTouchable(true);// 以及下一句 同时写才会有效
            popupArea.setFocusable(true);// 获取焦点
            popupArea.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                }
            });
        }

        RecyclerView mRecyclerView = (RecyclerView) rootArea.findViewById(R.id.recyclerview);
        mLayoutManager = new StaggeredGridLayoutManager(4,
                StaggeredGridLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(mLayoutManager);

        mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        AreaEntity.DataEntity areaEntity = areaList.get(position);
                        if (areaEntity != null) {
                            tvProvince.setText(areaEntity.getCarPlateGeoName());
                            provinceId = String.valueOf(areaEntity.getGeoId());
                        }
                        popupArea.dismiss();
                    }
                })
        );

        mAdapter = new PopupAdapter(this, areaList);
        mRecyclerView.setAdapter(mAdapter);

        popupArea.showAsDropDown(tvProvince);
    }

    private void initShortProvinceCode() {

        if (rootShortArea == null || popupShortArea == null) {
            rootShortArea = getLayoutInflater().inflate(R.layout.popup_list, null);
            // 创建PopupWindow对象
            popupShortArea = new PopupWindow(rootShortArea, ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            // popupArea.setAnimationStyle(R.anim.in);
            popupShortArea.setBackgroundDrawable(new BitmapDrawable());// 点击窗口外消失
            popupShortArea.setOutsideTouchable(true);// 以及下一句 同时写才会有效
            popupShortArea.setFocusable(true);// 获取焦点
            popupShortArea.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                }
            });
        }

        RecyclerView mRecyclerView = (RecyclerView) rootShortArea.findViewById(R.id.recyclerview);
        sLayoutManager = new StaggeredGridLayoutManager(4,
                StaggeredGridLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(sLayoutManager);

        final List<AreaEntity.DataEntity> listData = new ArrayList<AreaEntity.DataEntity>();
        int len = Constants.PROVINCE_SHORT_CODE.length;
        for (int i = 0; i < len; i++) {
            AreaEntity.DataEntity hmItem = new AreaEntity.DataEntity();
            hmItem.setCarPlateGeoName(Constants.PROVINCE_SHORT_CODE[i]);
            listData.add(hmItem);
        }

        mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        AreaEntity.DataEntity areaEntity = listData.get(position);
                        if (areaEntity != null) {
                            tvCityCode.setText(areaEntity.getCarPlateGeoName());
                        }
                        popupShortArea.dismiss();
                    }
                })
        );

        sAdapter = new PopupAdapter(this, listData);
        mRecyclerView.setAdapter(sAdapter);

        popupShortArea.showAsDropDown(tvProvince);
    }

    @Override
    @OnClick({R.id.tv_car_province, R.id.iv_car_province, R.id.tv_short_province, R.id.iv_short_province, R.id.btn_confirm,R.id.tv_car_no})
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.tv_car_province:
                getAreaData();
                break;
            case R.id.iv_car_province:
                getAreaData();
                break;
            case R.id.tv_short_province:
                initShortProvinceCode();
                break;
            case R.id.iv_short_province:
                initShortProvinceCode();
                break;
            case R.id.btn_confirm:
                createCust();
                break;
            case R.id.tv_car_no:
                new CarNumberKeyBoardView(ReceivingCarActivity.this, etCarNo, mKeyboardView).showKeyboard();
                break;
            default:
                break;
        }
    }

    private void getAreaData() {

        ReceivingApi service = ReceivingService.createReceivingService();
        service.getAreaResult()
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<AreaEntity>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(AreaEntity areaEntity) {

                        String retCode = areaEntity.getIs_successful();
                        if ("1".equals(retCode)) {
                            areaList = areaEntity.getData();
                            //    mAdapter.notifyDataSetChanged();
                            initPopup();
                        }
                    }
                });
    }

    private void getLocAreaInfo() {
        JSONObject json = null;

        try {
            json = new JSONObject();
            json.put("latitude", BaseApplication.getInstance().getPreference().getString(BaseConfig.LOCATION_LATITUDE,"39.9081726"));
            json.put("longitude", BaseApplication.getInstance().getPreference().getString(BaseConfig.LOCATION_LONGITUDE,"116.3979471"));

        } catch (JSONException e) {
            e.printStackTrace();
        }

        ReceivingApi service = ReceivingService.createReceivingService();
        service.getLocAreaInfo(json.toString())
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LocAreaInfoEntity>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(LocAreaInfoEntity locAreaInfoEntity) {

                        String retCode = locAreaInfoEntity.getIs_successful();
                        if ("1".equals(retCode)) {
                            provinceId = locAreaInfoEntity.getCityInfoMap().getPROVINCE_ID();
                            tvProvince.setText(locAreaInfoEntity.getCityInfoMap().getCAR_PLATE_GEO_NAME());
                            tvCityCode.setText(locAreaInfoEntity.getCityInfoMap().getPLATE_TYPE_CODE());
                        } else {
                            tvProvince.setText(null);
                            tvCityCode.setText(null);
                        }
                    }
                });
    }

    private void createCust(){

        if(CommonUtils.isEmpty(tvProvince.getText().toString())){
            showToast("请选择车牌所属地简称");
            return;
        }
        if(CommonUtils.isEmpty(tvCityCode.getText().toString())){
            showToast("请选择所属地编码");
            return;
        }
        if(CommonUtils.isEmpty(etCarNo.getText().toString())){
            showToast("请输入车牌号码");
            return;
        }
        if(etCarNo.getText().toString().length() == 0){
            showToast("请输入车牌号码");
            return;
        }
        if (etCarNo.getText().toString().length() != 5) {
            showToast("请输入正确的车牌号码");
            return;
        }
        if(!tvProvince.getText().equals("粤")){
            if(etCarNo.getText().toString().contains("港") || etCarNo.getText().toString().contains("澳")){
                showToast("请输入正确的车牌号码");
                return;
            }
        }
        waitDialog = DialogHelp.getWaitDialog(this,"正在提交，请稍后...");
        waitDialog.show();
        JSONObject json = null;
        try {
            json = new JSONObject();
            json.put("plateTypeCode", tvCityCode.getText().toString());
            json.put("provinceId", provinceId);
            json.put("carPlateNum", etCarNo.getText().toString());
            json.put("storeId", BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getStoreId());
            json.put("tenantId", BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getTenantId());
            json.put("carModelId","100479");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ReceivingApi service = ReceivingService.createReceivingService();
        service.createNewStoreCustomer(json.toString())
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<StoreCustEntity>() {
                    @Override
                    public void onCompleted() {
                        waitDialog.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        waitDialog.dismiss();
                    }

                    @Override
                    public void onNext(StoreCustEntity storeCustEntity) {
                        waitDialog.dismiss();
                        String retCode = storeCustEntity.getIs_successful();
                        if ("1".equals(retCode)) {
                            Bundle data = new Bundle();
                            CustomerEntity.StoreCustomerListBean bean  =  new CustomerEntity.StoreCustomerListBean();
                            bean.setCAR_PLATE_NUM(storeCustEntity.getStoreCustomerInfo().getCAR_PLATE_NUM());
                            bean.setCUST_CM_ID(storeCustEntity.getStoreCustomerInfo().getCUST_CM_ID());
                            bean.setCUSTOMER_ID(storeCustEntity.getStoreCustomerInfo().getCUSTOMER_ID());
                            bean.setCUSTOMER_NAME("散客");
                            Intent intent = getIntent();
                            data.putSerializable("customer", bean);
                            intent.putExtras(data);
                            setResult(RESULT_OK,intent);
                            finish();
                        } else {
                            showToast(storeCustEntity.getResult());
                        }
                    }
                });
    }
}
